﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;

namespace WellBuilt.RequestHelper
{
    /// <summary>
    /// 回执对象
    /// </summary>
    public class ResultMessage
    {
        /// <summary>
        /// 状态码
        /// </summary>
        public ResultCode Code { get; set; }
        /// <summary>
        /// 返回数据
        /// </summary>
        public object Data { get; set; }
        /// <summary>
        /// 提示信息
        /// </summary>
        public string Msg { get; set; }

        public ResultMessage SetResultMessage(ResultCode code, object data, string msg)
        {
            Code = code;
            Data = data;
            Msg = msg;
            return this;
        }        
    }

    public enum ResultCode
    {
        [Description("成功")]
        SUCCESS = 200,

        [Description("失败")]
        FAIL = 400,

        [Description("请求不合理，服务器拒绝执行")]
        UNAUTHORIZED = 403,

        [Description("找不到所需数据")]
        NOT_FOUND = 404,

        [Description("服务器内部错误")]
        INTERNAL_SERVER_ERROR = 500
    }
    /// <summary>
    /// 状态码的描述信息
    /// </summary>
    public static class CodeInfo
    {
        /// <summary>
        /// 获取枚举的描述信息(通过反射使特性生效)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(object value)
        {
            if (value == null)
                return string.Empty;

            Type type = value.GetType();
            var fieldInfo = type.GetField(Enum.GetName(type, value));
            if (fieldInfo != null)
            {
                if (Attribute.IsDefined(fieldInfo, typeof(DescriptionAttribute)))
                {
                    var description = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;

                    if (description != null)
                        return description.Description;
                }
            }
            return string.Empty;
        }
    }
}
